<template>
  <div>
    <!-- 使用v-if和key来确保组件完全重新创建 -->
    <template v-if="modalVisible">
      <SubProjectsModal 
        :key="`modal-${modalKey}`"
        :projectId="projectId" 
        :projectName="projectName" 
        :isEdit="isEdit" 
        :editData="currentEditData" 
        @success="onModalSuccess" 
        @close="closeModal" 
      />
    </template>
    
    <a-button type="primary" @click="handleAddSubProject">新增子项目</a-button>
    <a-button type="primary" style="margin-left: 8px" @click="handleBatchCreateSubProjectTeam">创建子项目团队</a-button>
    <BasicTable :columns="columns" :dataSource="subProjects" :rowSelection="rowSelection">
      <template #action="{ record }">
        <div style="width: 100%; display: flex; align-items: center; padding-left: 12px;">
          <a @click="handleEdit(record)" style="font-weight: 500; font-size: 14px;">编辑</a>
          <a-dropdown>
            <a class="ant-dropdown-link" @click.prevent style="display: flex; align-items: center; font-size: 14px; margin-left: 8px;">
              更多 <DownOutlined style="font-size: 12px; margin-left: 2px;" />
            </a>
            <template #overlay>
              <a-menu>
                <a-menu-item @click="handleDetail(record)">详情</a-menu-item>
                <a-menu-item @click="handleDelete(record)">删除</a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </div>
      </template>
    </BasicTable>
  </div>
</template>

<script setup>
import { ref, watch, nextTick } from 'vue'
import { BasicTable } from '/@/components/Table'
import SubProjectsModal from './SubProjectsModal.vue'
import { findAllSubProjectsById, createSubProjectTeam, batchDeleteSubProjects } from '../Projects.api'
import { Modal, Input, message } from 'ant-design-vue'
import { h } from 'vue'
import { CloseOutlined } from '@ant-design/icons-vue'
import { DownOutlined } from '@ant-design/icons-vue'

const props = defineProps({ projectId: String, projectName: String })
const subProjects = ref([])
const modalVisible = ref(false)
const isEdit = ref(false)
const currentEditData = ref({})
const modalKey = ref(0) // 添加key用于强制重新渲染modal组件

const columns = [
  { title: '创建人', dataIndex: 'createBy' },
  { title: '更新人', dataIndex: 'updateBy' },
  { title: '所属部门', dataIndex: 'sysOrgCode' },
  { title: '关联项目', dataIndex: 'projectId' },
  { title: '关联项目名称', dataIndex: 'taskName' },
  { title: '子项目名称', dataIndex: 'subProjectName' },
  { title: '子项目内容', dataIndex: 'subProjectContent' },
  { 
    title: '子项目金额', 
    dataIndex: 'subProjectAmount',
    customRender: ({ text }) => {
      if (text === null || text === undefined || text === '') {
        return '0.00';
      }
      return parseFloat(text).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
    }
  },
  { title: '操作', dataIndex: 'action', key: 'action', width: 120, slots: { customRender: 'action' } }
]

const selectedRowKeys = ref([])
const selectedRows = ref([])
const rowSelection = {
  type: 'checkbox',
  selectedRowKeys: selectedRowKeys.value,
  onChange: (keys, rows) => {
    selectedRowKeys.value = keys
    selectedRows.value = rows
    console.log('选中的子项目行keys:', keys)
    console.log('选中的子项目行数据:', rows)
  }
}

const emit = defineEmits(['refresh', 'success', 'close'])

// 关闭模态框
function closeModal() {
  modalVisible.value = false;
}

// 模态框成功回调
function onModalSuccess() {
  fetchSubProjects();
}

// 获取子项目数据
function fetchSubProjects() {
  if (!props.projectId) return
  
  // 显示加载状态
  const loadingMessage = message.loading('正在加载子项目数据...', 0);
  
  findAllSubProjectsById({ projectId: props.projectId })
    .then(res => {
      // 修复数据处理逻辑，确保正确获取子项目列表
      if (res && res.result) {
        subProjects.value = res.result;
      } else if (Array.isArray(res)) {
        subProjects.value = res;
      } else {
        subProjects.value = [];
      }
      
      // 重置选中状态
      selectedRowKeys.value = [];
      selectedRows.value = [];
      
      // 通知父组件刷新
      emit('refresh');
      console.log('subProjects:', subProjects.value);
    })
    .catch(error => {
      console.error('获取子项目列表失败:', error);
      message.error('获取子项目列表失败');
    })
    .finally(() => {
      // 关闭加载提示
      loadingMessage();
    });
}

// 打开模态框前的准备工作
function prepareAndOpenModal(isEditMode, data = {}) {
  // 确保模态框是关闭的
  modalVisible.value = false;
  
  // 使用nextTick确保DOM更新
  nextTick(() => {
    // 增加key以强制重新创建组件
    modalKey.value += 1;
    
    // 设置编辑模式和数据
    isEdit.value = isEditMode;
    currentEditData.value = isEditMode ? { ...data } : {};
    
    // 最后打开模态框
    setTimeout(() => {
      modalVisible.value = true;
    }, 50); // 添加一点延迟，确保DOM完全更新
  });
}

// 新增子项目
function handleAddSubProject() {
  prepareAndOpenModal(false);
}

// 编辑子项目
function handleEdit(row) {
  prepareAndOpenModal(true, row);
}

// 查看详情
function handleDetail(row) {
  // 使用Modal.info展示详情，美化样式使其更符合设计要求
  Modal.info({
    title: '子项目详情',
    width: 600,
    centered: true,
    icon: null, // 移除默认图标
    maskClosable: true,
    okText: '确定',
    bodyStyle: { padding: '24px 24px 12px', background: '#fafbfc', borderRadius: '0 0 8px 8px' },
    content: h('div', { style: 'padding: 0' }, [
      // 使用表格样式展示详情
      h('div', { style: 'display: flex; flex-direction: column; gap: 16px;' }, [
        // 基本信息
        h('div', { style: 'background-color: #fff; border-radius: 8px; padding: 16px; box-shadow: 0 1px 3px rgba(0,0,0,0.05);' }, [
          h('div', { style: 'font-size: 16px; font-weight: 500; color: #333; margin-bottom: 16px; padding-bottom: 10px; border-bottom: 1px solid #f0f0f0;' }, '基本信息'),
          
          // 子项目名称
          h('div', { style: 'display: flex; margin-bottom: 16px;' }, [
            h('div', { style: 'width: 120px; color: #666; text-align: right; padding-right: 16px;' }, '子项目名称:'),
            h('div', { style: 'flex: 1; color: #333; font-weight: 500;' }, row.subProjectName || '-')
          ]),
          
          // 子项目内容
          h('div', { style: 'display: flex; margin-bottom: 16px;' }, [
            h('div', { style: 'width: 120px; color: #666; text-align: right; padding-right: 16px;' }, '子项目内容:'),
            h('div', { style: 'flex: 1; color: #333;' }, row.subProjectContent || '-')
          ]),
          
          // 子项目金额
          h('div', { style: 'display: flex; margin-bottom: 16px;' }, [
            h('div', { style: 'width: 120px; color: #666; text-align: right; padding-right: 16px;' }, '子项目金额:'),
            h('div', { style: 'flex: 1; color: #333; font-weight: 500; color: #1890ff;' }, 
              row.subProjectAmount ? 
                `¥ ${parseFloat(row.subProjectAmount).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}` : 
                '¥ 0.00'
            )
          ]),
          
          // 关联项目
          h('div', { style: 'display: flex; margin-bottom: 0;' }, [
            h('div', { style: 'width: 120px; color: #666; text-align: right; padding-right: 16px;' }, '关联项目:'),
            h('div', { style: 'flex: 1; color: #333;' }, row.taskName || '-')
          ])
        ]),
        
        // 创建信息
        h('div', { style: 'background-color: #fff; border-radius: 8px; padding: 16px; box-shadow: 0 1px 3px rgba(0,0,0,0.05);' }, [
          h('div', { style: 'font-size: 16px; font-weight: 500; color: #333; margin-bottom: 16px; padding-bottom: 10px; border-bottom: 1px solid #f0f0f0;' }, '创建信息'),
          
          // 创建人
          h('div', { style: 'display: flex; margin-bottom: 16px;' }, [
            h('div', { style: 'width: 120px; color: #666; text-align: right; padding-right: 16px;' }, '创建人:'),
            h('div', { style: 'flex: 1; color: #333;' }, row.createBy || '-')
          ]),
          
          // 创建时间
          h('div', { style: 'display: flex; margin-bottom: 16px;' }, [
            h('div', { style: 'width: 120px; color: #666; text-align: right; padding-right: 16px;' }, '创建时间:'),
            h('div', { style: 'flex: 1; color: #333;' }, row.createTime || '-')
          ]),
          
          // 更新人
          h('div', { style: 'display: flex; margin-bottom: 16px;' }, [
            h('div', { style: 'width: 120px; color: #666; text-align: right; padding-right: 16px;' }, '更新人:'),
            h('div', { style: 'flex: 1; color: #333;' }, row.updateBy || '-')
          ]),
          
          // 更新时间
          h('div', { style: 'display: flex; margin-bottom: 0;' }, [
            h('div', { style: 'width: 120px; color: #666; text-align: right; padding-right: 16px;' }, '更新时间:'),
            h('div', { style: 'flex: 1; color: #333;' }, row.updateTime || '-')
          ])
        ])
      ])
    ])
  });
}

// 删除子项目
function handleDelete(row) {
  if (!row.id) {
    message.error('子项目ID不存在');
    return;
  }
  Modal.confirm({
    title: '确认删除',
    content: '确定要删除该子项目吗？',
    onOk: async () => {
      try {
        await batchDeleteSubProjects({ ids: [row.id] }, () => {
          message.success('删除成功');
          fetchSubProjects();
          emit('refresh');
        });
      } catch (e) {
        message.error('删除失败');
      }
    }
  });
}

// 创建项目团队（未使用）
function handleCreateTeam(row) {
  message.info('创建项目团队：' + (row.subProjectName || ''));
}

// 批量创建子项目团队
function handleBatchCreateSubProjectTeam() {
  if (!selectedRows.value.length) {
    message.warning('请先选择至少一个子项目')
    return
  }
  let teamName = ''
  let modalInstance = null
  const handleClose = () => {
    if (modalInstance) {
      modalInstance.destroy()
    }
  }
  modalInstance = Modal.confirm({
    title: '创建子项目团队',
    icon: null, // 去掉左侧图标
    centered: true,
    closable: true,
    closeIcon: h(CloseOutlined, { class: 'custom-team-modal-close', onClick: handleClose }),
    content: h('div', { class: 'custom-team-modal-content' }, [
      h('div', { class: 'custom-team-modal-divider' }),
      h('div', { class: 'custom-team-modal-form-row' }, [
        h('label', { class: 'custom-team-modal-label' }, '团队名称：'),
        h(Input, {
          autofocus: true,
          placeholder: '请输入团队名称',
          class: 'custom-team-modal-input',
          onInput: e => { teamName = e.target.value }
        })
      ])
    ]),
    okButtonProps: { style: 'padding: 4px 18px; font-size: 14px; border-radius: 4px;' },
    cancelButtonProps: { style: 'padding: 4px 18px; font-size: 14px; border-radius: 4px;' },
    bodyStyle: { padding: '32px 32px 24px 32px', background: '#fafbfc', borderRadius: '10px' },
    onOk: async () => {
      if (!teamName) {
        message.error('团队名称不能为空')
        return Promise.reject()
      }
      // 这里只取第一个选中的子项目为例，如需批量可遍历 selectedRows.value
      const row = selectedRows.value[0]
      await createSubProjectTeam({ subProjectId: row.id, projectId: row.projectId, teamName })
      message.success('创建子项目团队成功')
    },
    // 允许点击右上角关闭
    onCancel: handleClose
  })
}

// 监听项目ID变化，获取子项目列表
watch(() => props.projectId, fetchSubProjects, { immediate: true })
</script>

<style scoped>
</style>
<style>
/* 全局样式，作用于Modal.confirm自定义内容 */
.custom-team-modal-content {
  display: flex;
  flex-direction: column;
  align-items: stretch;
  justify-content: flex-start;
  padding: 32px 0 0 0;
  position: relative;
}
.custom-team-modal-divider {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 1px;
  background: #eaeaea;
  opacity: 0.7;
  border-radius: 1px;
  margin-bottom: 16px;
}
.custom-team-modal-form-row {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-top: 16px;
  margin-bottom: 28px;
}
.custom-team-modal-label {
  min-width: 90px;
  max-width: 120px;
  text-align: right;
  font-size: 15px;
  color: #222;
  font-weight: 500;
  margin-right: 8px;
  line-height: 32px;
}
.custom-team-modal-input {
  flex: 1;
  padding: 8px 12px;
  font-size: 15px;
  border-radius: 6px;
  box-shadow: none;
  outline: none;
  background: #fff;
  min-width: 0;
}
.custom-team-modal-close {
  font-size: 18px;
  color: #999;
  cursor: pointer;
  transition: color 0.2s;
  position: absolute;
  top: 16px;
  right: 16px;
  z-index: 10;
}
.custom-team-modal-close:hover {
  color: #333;
}
</style> 